// pages/Visit/Visit.js
const App = getApp()
const server = App.path.Server

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 设置swiper高度
        windowHeight: App.systemInfo.windowHeight - 45,
        // 设置tab bar激活项目
        tabBarActiveIndex: 0,
        // 设置tab bar移动距离
        tabBarPosition: 0,
        // 设置tab bar横条left
        tabBarBottomLeft: 0,
        // 设置tab bar横条位移
        tabBarBottomPosition: 0,
        // 设置swiper当前page
        currentIndex: 0,
        // 设置内容scroll-view的距离顶部的位置
        scrollViewPosition: 0,
        // 750 当前设备宽度比
        v750: 750 / App.systemInfo.windowWidth,
        // 记录特殊情况页
        urlRecord: App.path.Record,
        // 存放tab bar栏目
        tabBarConfig: [],
        // 存放页面配置信息
        config: [],
        // 查访老人id
        uid: '',
        // 存放结果
        result: {},
        // 存放失效页面
        disables: {},
        // 放老人的id
        man: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // console.log(this.data.config)
        // console.log('onLoad')
        this.setData(options)
        this.getPageConfigDataFromPort()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // console.log('onReady')
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    // 轮播切换回调
    swiperCallback(e) {
        if (e.detail.source === "touch") {
            this.tabBarMoveEvent(e.detail.current);
            this.setData({
                tabBarActiveIndex: e.detail.current,
                scrollViewPosition: 0
            })
        }
    },

    // tab bar点击事件
    tabBarCatchtap(e) {
        let index = e.target.dataset.index;
        this.tabBarMoveEvent(index);
        this.setData({
            tabBarActiveIndex: index,
            currentIndex: index,
            scrollViewPosition: 0
        })
    },

    // tab bar移动事件
    tabBarMoveEvent(index) {
        let ww = App.systemInfo.windowWidth;// 设备宽度
        let px = 174 / this.data.v750;// 一个tab bar项目多宽
        let vw = px * this.data.tabBarConfig.length > ww ? px * this.data.tabBarConfig.length : ww;// tab bar 宽度
        let nowCenterPosition = vw > ww ? px * index + px / 2 : ww / 2;// 当前中点位置
        let needMove = nowCenterPosition > ww / 2;// 中点大于设备宽度一半需要移动
        let notMove = vw - nowCenterPosition < ww / 2;// 移动后是否超过溢出
        // console.log(`当前设备宽度为${ww},导航栏宽度${vw},中点位置${nowCenterPosition},是否需要移动${needMove},是否移动后溢出${notMove}`)
        if (needMove) {
            if (notMove) {
                // 如果溢出,移动vw减去ww的一半
                this.setData({
                    tabBarPosition: vw - ww / 2
                })
            }
            else {
                // 不溢出,移动当前减去ww的一半
                this.setData({
                    tabBarPosition: nowCenterPosition - ww / 2
                })
            }
        }
        else {
            // 不需要移动则为0
            this.setData({
                tabBarPosition: 0
            })
        }
    },

    // tab bar下横条位置计算
    tabBarBottomViewPosition() {
        // transform: translateX(px); left: px;
        let num = this.data.tabBarConfig.length;//tab bar的个数
        let ww = App.systemInfo.windowWidth;// 设备宽度
        let px = 174 / this.data.v750;// 一个tab bar项目多宽
        let hw = 80 / this.data.v750 / 2;// 横条宽度的一半
        let isFlexSpaceAround = num * px > ww;// 是否会有间隙
        if (!isFlexSpaceAround) {
            // 有间隙,left单个项目所占宽度的一半(ww/num/2-hw),位移第n个项目的宽度(ww/num)
            this.setData({
                tabBarBottomLeft: ww / num / 2 - hw,
                tabBarBottomPosition: ww / num
            })
        }
        else {
            // 无间隙,left 47/this.data.v750,位移n个项目的宽度px
            this.setData({
                tabBarBottomLeft: 47 / this.data.v750,
                tabBarBottomPosition: px
            })
        }
    },

    // 获取数据
    getPageConfigDataFromPort() {
        const that = this
        wx.request({
            url: server + '/v1/order/getView/' + that.data.uid,
            header: {
              'Authorization': 'Bearer ' + App.globalData.token.access_token
            },
            complete(res) {
                App.judgeCode(res, function(_res){
                    let configData = _res.data
                    let tabBarArray = []
                    let result = {}
                    let disables = that.data.disables
                    configData.map((item) => {
                        tabBarArray.push(item.title)
                        disables[item.uid] = item.hasFinish
                        let _answer = new Answer()
                        _answer.orderId = that.data.uid
                        _answer.questionlistId = item.uid

                        result[item.uid] = _answer
                    })
                    that.setData({
                        tabBarConfig: tabBarArray,
                        config: configData,
                        result: result,
                        disables: disables,
                    })
                    that.tabBarBottomViewPosition()
                })
                wx.hideLoading()
            },
        })
    },

    // 提交当前页面
    submitCurrentPage(e) {
        console.log(e)
        const that = this;
        const obj = e.detail.value
        // 提交的答案集合
        const answers = that.data.result[e.target.dataset.page]

        //检查 填空的需要前端循环检查
        for (let index in that.data.config){
            if (that.data.config[index].uid === answers.questionlistId){
                //这是此时的选项卡
                let inputKard = that.data.config[index].questionList;

                for (let key in inputKard){
                    if (inputKard[key].type === 'form'){
                        //获取到的选项
                        let options = inputKard[key].options;

                        for (let script in options){
                            //循环填空 看是否已经填写了值
                            let hasWord = false
                            for (let answerKey in answers.answerList){
                                if (answers.answerList[answerKey].optionId === options[script].uid){
                                    //有回答答案
                                    hasWord = true
                                    //判断是否在范围之内
                                    if (options[script].upMax){
                                        //允许输入的最大值
                                        if (parseFloat(answers.answerList[answerKey].answer) >= parseFloat(options[script].upMax)){
                                            wx.showModal({
                                                title: '错误',
                                                content: inputKard[key].title + ':'+options[script].title + '填写错误,最大值为:' + options[script].upMax,
                                                success: function (res) {
                                                    if (res.confirm) {
                                                        return
                                                    } else if (res.cancel) {
                                                        return
                                                    }
                                                }
                                            })
                                        }
                                    }

                                    if (options[script].downMin) {
                                        //允许输入的最大值
                                        if (parseFloat(answers.answerList[answerKey].answer) <= parseFloat(options[script].upMax)) {
                                            wx.showModal({
                                                title: '错误',
                                                content: inputKard[key].title+':'+options[script].title + '填写错误,最小值为:' + options[script].downMin,
                                                success: function (res) {
                                                    if (res.confirm) {
                                                        return
                                                    } else if (res.cancel) {
                                                        return
                                                    }
                                                }
                                            })
                                        }
                                    }
                                }
                            }

                            if (!hasWord){
                                wx.showModal({
                                    title: '错误',
                                    content: inputKard[key].title + ':' + options[script].title + '未填写,请填写!' ,
                                    success: function (res) {
                                        if (res.confirm) {
                                            return
                                        } else if (res.cancel) {
                                            return
                                        }
                                    }
                                })
                            }
                        }
                    }
                }
            }
        }

        if (that.data.tabBarConfig.length !== e.target.dataset.index + 1) {
            wx.showModal({
                title: '',
                content: '是否确认提交',
                cancelText: '取消',
                cancelColor: '#424242',
                confirmText: '提交',
                confirmColor: '#44B46E',
                success(res) {
                    if (res.confirm) {
                        wx.request({
                            url: server + '/v1/answer/commit',
                            method: "POST",
                            header: {
                              'Authorization': 'Bearer ' + App.globalData.token.access_token
                            },
                            data: that.data.result[e.target.dataset.page],
                            complete(res) {
                                console.log(res)
                                App.judgeCode(res, function(_res){
                                    let disables = that.data.disables
                                    disables[e.target.dataset.page] = true
                                    that.setData({
                                        disables: disables
                                    })
                                    wx.showModal({
                                        title: '提交成功',
                                        content: '请选择是否继续下一项查访',
                                        cancelText: '老人主页',
                                        cancelColor: '#424242',
                                        confirmText: '继续查访',
                                        confirmColor: '#44B46E',
                                        success(res1) {
                                            console.log('--------------------')
                                            console.log(res1)
                                            if (res1.cancel) {
                                                wx.navigateTo({
                                                    url: '/pages/ManHome/Home?uid=' + that.data.man,
                                                })
                                            }
                                            if (res1.confirm) {
                                                if (that.data.tabBarConfig[e.target.dataset.index + 1]) {
                                                    that.setData({
                                                        tabBarActiveIndex: e.target.dataset.index + 1,
                                                        currentIndex: e.target.dataset.index + 1,
                                                        scrollViewPosition: 0
                                                    })
                                                }
                                            }
                                        }
                                    })
                                })
                            }
                        })
                    }
                }
            })
        }
        else {
            wx.showModal({
                title: '',
                content: '是否确认提交',
                cancelText: '取消',
                cancelColor: '#424242',
                confirmText: '提交',
                confirmColor: '#44B46E',
                success(res) {
                    if (res.confirm) {
                        wx.request({
                            url: server + '/v1/answer/commit',
                            header: {
                              'Authorization': 'Bearer ' + App.globalData.token.access_token
                            },
                            method: "POST",
                            data: that.data.result[e.target.dataset.page],
                            complete(res) {
                                App.judgeCode(res, function(_res){
                                    let disables = that.data.disables
                                    disables[e.target.dataset.page] = true
                                    that.setData({
                                        disables: disables
                                    })
                                    wx.showToast({
                                        title: '提交成功',
                                        icon: 'success',
                                        success() {
                                            setTimeout(() => wx.navigateBack(), 1500)
                                        }
                                    })
                                })
                            }
                        })
                    }
                }
            })
        }
    },

    // 获取问卷数据
    setResult(e) {
        // console.log(e)
        // string 答案 打钩的是1，填空的是文字
        // obj.answer
        // string 选项 id questionList.item.options.item.uid
        // obj.optionId
        // string 问题 id questionList.item.uid
        // obj.questionId
        let result = this.data.result
        let data = e.target.dataset
        let page = result[data.page]
        let list = result[data.page].answerList
        let had = false
        let now_index = 0
        list.map((item, index) => {
            if (item.optionId == data.uid) {
                had = true
                now_index = index
            }
        })
        // console.log(had, now_index)
        if (e.type === 'tap') {
            if (!had) {
                add(page, { answer: 1, optionId: data.uid, questionId: data.question })
            }
            else {
                list.splice(now_index, 1)
            }
        }
        else if (e.type === 'input') {
            // console.log(e.target.dataset)
            // console.log(e.detail.value)
            if (!had) {
                add(page, { answer: e.detail.value, optionId: data.uid, questionId: data.question })
            }
            else {
                list[now_index].answer = e.detail.value
            }
        }
        else if (e.type === 'change') {
            // console.log(e)
            list.map((item, index) => {
                if (item.questionId == data.question) {
                    had = true
                    now_index = index
                }
            })
            if (had) { list.splice(now_index, 1) }
            add(page, { answer: 1, optionId: e.detail.value, questionId: data.question })
        }
        // console.log(result)

        this.setData({
            result: result
        })
    },

    // 上传图片页面调用函数（强耦合）
    _setPhotosToData(page, data){
        console.log(page)
        console.log(data)
        let temp = this.data.result
        temp[page].answerSub = data
        this.setData({
            result: temp
        })
    }
})

// 提交页面数据对象
class Answer {
    constructor() {
        this.answerList = []
        this.answerSub = {
            "images": "", // string 图片 用,间隔
            "oldmanState": "", // string 老人状态  0正常 1 异常
            "remark": ""  // string textarea
        }
        this.orderId = '' // string url uid
        this.questionlistId = '' // string 当前page uid
    }
}
const add = (_this, obj) => {
    // string 答案 打钩的是1，填空的是文字
    // obj.answer
    // string 选项 id questionList.item.options.item.uid
    // obj.optionId
    // string 问题 id questionList.item.uid
    // obj.questionId
    typeof obj !== 'object' ? console.warn('传参类型错误') : obj.answer ? obj.optionId ? obj.questionId ? _this.answerList.push(obj) : console.warn('object.questionId不存在') : console.warn('object.optionId不存在') : console.warn('object.answer不存在')
}